<%@page contentType="text/html" import="java.io.*,javax.xml.transform.*,javax.xml.transform.stream.*"%>
<%@page pageEncoding="UTF-8"%>
<%!
   static class XMLFilter implements FilenameFilter {
      public boolean accept(File dir, String name) {
         return name.endsWith(".xml");
      }
   }
   
   Transformer model2xhtml;
   File transformFile;
   long timestamp;
   
   public void jspInit() {
      model2xhtml = null;
      ServletConfig config = getServletConfig();
      transformFile = new File(config.getServletContext().getRealPath("models2xhtml.xsl"));
      checkTransformer();
   }
   
   
   public void checkTransformer() {
      if (model2xhtml!=null && transformFile.lastModified()>timestamp) {
         model2xhtml = null;
      }
      if (model2xhtml==null) {
         ServletConfig config = getServletConfig();
         try {
            timestamp = transformFile.lastModified();

            TransformerFactory tfactory = TransformerFactory.newInstance();
            model2xhtml = tfactory.newTransformer(new StreamSource(transformFile));
         } catch (Exception ex) {
            config.getServletContext().log("Cannot load stylesheet.",ex);
         }
      }
   }
%>
<%
   checkTransformer();
   if (model2xhtml!=null) {
      ServletContext context = getServletContext();
      String path = context.getInitParameter("model-repository");
      File repository = new File(context.getRealPath(path));
      File [] models = repository.listFiles(new XMLFilter());
      StringBuffer sb = new StringBuffer();
      sb.append("<models>");
      for (int i=0; i<models.length; i++) {
         sb.append("<model rel='");
         sb.append(path+'/'+models[i].getName());
         // This is a hack since JAXP isn't using the base URI properly
         sb.append("' href='");
         sb.append(models[i].getAbsolutePath());
         sb.append("'/>");
      }
      sb.append("</models>");

      StreamResult sout = new StreamResult(out);
      StreamSource in = new StreamSource(new StringReader(sb.toString()));
      in.setSystemId(path);
      model2xhtml.transform(in,sout);
   } else {
      out.println("<p>Stylesheet not loaded during initialization.</p>");
   }
   
%>
